package com.sci.controller;

import com.sci.client.UserServiceClient;
import com.sci.entity.CommonResult;
import com.sci.entity.User;
import com.sci.mapper.UserMapper;
import com.sci.util.CookieUtil;
import com.sci.util.JwtTokenUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private UserMapper userMapper;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private CookieUtil cookieUtil;

    @Resource
    private UserServiceClient userService;

    @PostMapping("/login")
    public CommonResult<String> login(
            @RequestParam(name = "wechatId") String wechatId,
            @RequestParam(name = "password") String password,
            HttpServletResponse response) {

        User user = userMapper.selectById(wechatId);
        if (user == null || !user.getPassword().equals(sha256(password))) {
            return new CommonResult<>(401, "用户名或密码错误", null);
        }

        // 生成访问令牌（24小时有效期）
        String accessToken = jwtTokenUtil.generateAccessToken(user);

        // 设置Cookie，有效期为24小时
        cookieUtil.setCookie(response, "access_token", accessToken, Duration.ofHours(24));

        return new CommonResult<>(200, "登录成功", accessToken);
    }

    @PostMapping("/register")
    public Boolean register(@RequestBody User user) {
        System.out.println("进入注册服务");
        return userService.register(user);
    }

    private String sha256(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(input.getBytes());
            StringBuilder hexString = new StringBuilder();

            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}